<template>
  <div class="topBg">
    <div
      style="
        width: 100vw;
        height: 95px;
        padding-top: 50px;
        position: relative;
        display: flex;
        justify-content: center;
        line-height: 64rpx;
      "
    >
      <div style="position: absolute; left: 30rpx; top: 105rpx">
        <u-icon
          @click="rightClick"
          name="arrow-left"
          color="#fff"
          size="44"
        ></u-icon>
      </div>
      <div style="color: #fff; font-size: 36rpx">订单详情</div>
    </div>
    <!--  <div style="height: 155rpx;width: 100vw;    display: flex;    align-items: center;">
            <div style="color: #fff;font-size: 20px;font-weight: 500;padding-left: 18px;padding-top: 20px;">
                <div style="font-style: 18px;font-weight: 600;    display: flex;
    align-items: center;"><img style="width: 18px;height: 18px;margin-right: 5px;" src="http://:41980/api/uploads/image/20240830/f537d1d6-d646-4e32-a954-dddffc515a0e.png" alt="">预约中...</div>
                <div style="font-size: 12px;margin-left: 23px;margin-top: 5px;">平台正在加急为您安排工作人员</div>
            </div>
        </div> -->
  </div>
  <uni-transition
    mode-class="zoom-in"
    needLayout="true"
    :show="orderData"
    :duration="500"
  >
    <view class="order_detail">
      <!-- Main Start -->
      <view class="flex pb-[30rpx]" style="margin-top: -90px">
        <image
          v-if="orderData.orderStatus === 0"
          class="header-image"
          src="/static/images/icon_pay.png"
        >
        </image>
        <image
          v-if="orderData.orderStatus === 1 || orderData.orderStatus === 2"
          class="header-image"
          src="/static/images/icon_wait.png"
        ></image>
        <image
          v-if="orderData.orderStatus === 3"
          class="header-image"
          src="/static/images/icon_success.png"
        >
        </image>
        <image
          v-if="orderData.orderStatus === 4"
          class="header-image"
          src="@/static/images/icon_close.png"
        >
        </image>
        <text class="ml-[15rpx] text-white">{{
          orderData.orderStatusName
        }}</text>
      </view>
      <view
        v-if="isBuy == 1 || BuyOrder.length > 0"
        class="card flex justify-between flex-wrap normal text-base"
        style="margin-top: 35px"
      >
        <view class="topImg">
          <img
            v-for="item in BuyOrder"
            :key="item.id"
            :src="baseUrl + 'api/uploads/' + item.image"
            class="img_border"
          />
          <template v-if="BuyOrder.length < BuyOrder[0].buyPeopleNum">
            <img
              v-for="(i, index) in BuyOrder[0].buyPeopleNum - BuyOrder.length"
              :key="index"
              :src="gIndexImage.img"
              class="img_border"
            />
          </template>
        </view>
        <view
          class="buyPeopleNum"
          v-if="BuyOrder[0].buyPeopleNum - BuyOrder.length > 0"
        >
          还差<span style="color: darkred">{{
            BuyOrder[0].buyPeopleNum - BuyOrder.length
          }}</span
          >人，赶快邀请好友来拼单吧
        </view>
        <view
          class="buyPeopleNum"
          v-else-if="BuyOrder[0].buyPeopleNum - BuyOrder.length == 0"
        >
          拼团成功！马上安排客服进行派单！
        </view>
        <view
          class="footer_button"
          v-if="BuyOrder[0].buyPeopleNum - BuyOrder.length > 0"
        >
          <button
            open-type="share"
            id="101"
            class="text-lg text-white leading-[80rpx] h-[80rpx]"
            @click="onbuyPeople()"
            style="
              background-image: url('http://mzd-admin.muzhandao.com/api/uploads/image/20241102/029ff3a7-ffc1-4a63-ae3f-45ccdffc2d01.png');
              background-size: 100% 100%;
              margin: 5px;
            "
          >
            邀请好友拼单
          </button>
        </view>
      </view>
      <!-- 地址卡片 -->
      <view class="card" style="margin-top: 10px">
        <view class="card--header" @click="clickcardheader(orderData)">
          <view class="title text-black">
            <img
              src="http://mzd-admin.muzhandao.com/api/uploads/image/20240905/7e483fd7-4b3d-45e7-b0bc-a3e7671bfd23.png"
              style="width: 36rpx; height: 36rpx; margin-right: 10rpx"
              alt=""
            />
            {{ orderData.province }}
            {{ orderData.city }}
            {{ orderData.district }}
            {{ orderData.address }}
          </view>
        </view>
        <view class="text-sm text-muted" style="padding-left: 27px">
          {{ orderData.contact }} {{ orderData.mobile }}
        </view>
      </view>

      <!-- 商品卡片 -->
      <view class="card">
        <view class="goods-item">
          <u-image
            :src="orderData.orderGoods?.imageUrl"
            width="160"
            height="160"
            border-radius="4"
          ></u-image>
          <view class="ml-[20rpx] mt-[4rpx]">
            <view class="flex justify-between title">
              <view class="goods-item--name truncate">{{
                orderData.orderGoods?.goodsName
              }}</view>
              <text>x{{ orderData.orderGoods?.goodsNum }}</text>
            </view>
            <view class="mt-[24rpx]">
              <price
                :price="orderData.orderGoods?.goodsPrice"
                :desc="orderData.orderGoods?.unitName"
              >
              </price>
            </view>
          </view>
        </view>
      </view>

      <!-- 上门时间 -->
      <view class="card normal text-base flex justify-between">
        <view style="display: flex; align-items: center"
          ><img
            src="http://mzd-admin.muzhandao.com/api/uploads/image/20240905/96906d63-dc4a-4e4b-bc57-fd45735cfe0b.png"
            style="width: 36rpx; height: 36rpx; margin-right: 10rpx"
            alt=""
          />上门时间</view
        >
        <view v-if="paytype != 2">
          {{ orderData.appointTime }} {{ orderData.weekDay }}
          {{ orderData.appointTimeStartStr }}-{{ orderData.appointTimeEndStr }}
        </view>
        <view class="" style="display: flex; align-items: center" v-else>
          <view class="flex">
            <text class="mr-[20rpx] text-sm text-black">{{ appointText }}</text>
            <u-icon
              @click="goPage(`/bundle/pages/appoint_time/index`)"
              name="arrow-right"
              color="#707070"
              size="22"
            ></u-icon>
          </view>
        </view>
      </view>

      <!-- 服务师傅 -->
      <template v-if="orderData?.staff">
        <view
          class="card normal text-base flex justify-between"
          v-for="staff in orderData.staff"
          :key="staff.id"
        >
          <view>订单详情</view>
          <view>{{ staff.name }} {{ staff.mobile }}</view>
        </view>
      </template>

      <!-- 我的核销码 -->
      <!-- <template v-if="orderData.orderStatus === 2">
                <view class="card normal text-base">
                    <view class="">
                        <view>我的核销码</view>
                    </view>

                    <view class="pt-[40rpx] flex justify-center">
                        <qrcode
                            ref="qrcode"
                            uni="px"
                            :val="orderData?.verificationCode"
                            :size="118 * 2"
                            :showLoading="false"
                        />
                    </view>

                    <view class="text-center p-[20rpx]">
                        核销码：{{ orderData.verificationCode }}
                    </view>
                </view>
            </template> -->

      <!-- 服务金额 -->
      <view class="card normal text-base">
        <view class="flex justify-between">
          <view>服务金额</view>
          <view>¥{{ orderData.orderAmount }}</view>
        </view>
        <view class="mt-[30rpx] flex justify-between">
          <view>实付金额</view>
          <view class="text-primary">¥{{ orderData.totalAmount }}</view>
        </view>
        <!-- <view class="mt-[30rpx] flex justify-between">
					<view>退款金额</view>
					<view class="text-primary">¥{{ orderData.totalAmount }}</view>
				</view> -->

        <view class="mt-[30rpx] flex justify-between">
          <view></view>
          <view class="text-primary">
            <button
              v-if="
                orderData.orderStatus === 3 &&
                (orderData.reviewStatus === null ||
                  orderData.reviewStatus === 0)
              "
              class="Btn evaluate bg-white text-sm text-muted leading-[60rpx] h-[60rpx] rounded-full"
              @click.stop="handleOrder(orderData.id)"
            >
              退款
            </button>
            <button
              v-if="orderData.orderStatus === 3 && orderData.reviewStatus === 1"
              class="Btn evaluate bg-white text-sm text-muted leading-[60rpx] h-[60rpx] rounded-full"
              @click.stop="uni.$u.toast('退款成功')"
            >
              退款成功
            </button>
            <button
              v-if="orderData.orderStatus === 3 && orderData.reviewStatus === 2"
              class="Btn evaluate bg-white text-sm text-muted leading-[60rpx] h-[60rpx] rounded-full"
              @click.stop="handleOrder(orderData.id)"
            >
              重新申请退款
            </button>
          </view>
        </view>
      </view>
      <!-- 这里填退款金额与备注 -->
      <view v-if="isToggle.orderId" class="card normal text-base">
        <view class="mt-[30rpx] flex justify-between">
          <view>请输入退款金额</view>
          <view class="text-primary">
            <uni-number-box
              :value="isToggle.refundAmount"
              :min="0"
              :max="orderData.totalAmount"
              :step="0.01"
              @change="bindChange"
            />
          </view>
        </view>
        <view class="mt-[30rpx] flex justify-between">
          <view>请输入申请退款备注</view>
          <view class="text-primary">
            <uni-easyinput
              class="uni-mt-5"
              trim="all"
              v-model="isToggle.remark"
              placeholder="请输入退款备注"
            ></uni-easyinput>
          </view>
        </view>
        <view class="mt-[30rpx] flex justify-between">
          <view></view>
          <view class="text-primary">
            <button
              class="Btn evaluate bg-white text-sm text-muted leading-[60rpx] h-[60rpx] rounded-full"
              @click.stop="dialogToggle()"
            >
              提交退款申请
            </button>
          </view>
        </view>
      </view>

      <!-- 备注 -->
      <view class="card flex justify-between flex-wrap normal text-base">
        <view>备注</view>
        <view style="width: 100%; word-wrap: break-word">{{
          orderData.userRemark
        }}</view>
      </view>

      <!-- 订单信息 -->
      <view class="card normal text-base">
        <view class="flex justify-between">
          <view>订单编号</view>
          <view>{{ orderData.sn }}</view>
        </view>
        <view class="mt-[30rpx] flex justify-between">
          <view>支付方式</view>
          <view>{{ orderData.payWayName }}</view>
        </view>
        <view class="mt-[30rpx] flex justify-between">
          <view>下单时间</view>
          <view>{{ orderData.createTime }}</view>
        </view>
        <view
          class="mt-[30rpx] flex justify-between"
          v-if="orderData.orderStatus === 3"
        >
          <view>完成时间</view>
          <view>{{ orderData.finishTime }}</view>
        </view>
        <view
          class="mt-[30rpx] flex justify-between"
          v-if="orderData.orderStatus === 4"
        >
          <view>关闭时间</view>
          <view>{{ orderData.cancelTime }}</view>
        </view>
      </view>

      <!-- Main End -->
    </view>
  </uni-transition>

  <!-- 输入框示例 -->
  <!-- Footer Start -->
  <view class="footer flex justify-end" v-if="orderData.orderStatus != 4">
    <order-footer
      :orderId="orderData.id"
      :orderStatus="orderData.orderStatus"
      :cancel="orderData.cancelBtn"
      :del="orderData.delBtn"
      :evaluate="orderData.commentBtn"
      :contact="orderData.contactBtn"
      :pay="orderData.payBtn"
      :mobile="null"
      :type="2"
      :paytype="paytype"
      :phoneToNumber="orderData?.mobile"
      :phoneFromNumber="orderData?.staff ? orderData?.staff[0].mobile : null"
      @refresh="initOrderDetail"
      @refreshQryy="refreshQryyfun"
    />
  </view>
  <!-- Footer End -->

  <!-- Component 支付 -->
  <payment
    v-if="payState.showPay || payState.showCheck"
    v-model:show="payState.showPay"
    v-model:show-check="payState.showCheck"
    :order-id="payState.orderId"
    :order_amount="orderData?.totalAmount"
    :from="payState.from"
    :redirect="payState.redirect"
    @success="handlePayResult"
    @close="handlePayResult"
    @fail="handlePayResult"
  />
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from "vue";
import { getgetIndexImage } from "@/api/shop";
import { onLoad, onUnload, onShow, onHide } from "@dcloudio/uni-app";
import {
  apiOrderDetail,
  getBuyOrder,
  apiordergetOrderRefund,
  apiorderrebates,
  apigetOrderupdate,
} from "@/api/order";
import Price from "@/components/price/index.vue";
import OrderFooter from "@/components/order-footer/index.vue";
import { ISBUY_ID, GOODS_ID } from "@/enums/cacheEnums";
import cache from "@/utils/cache";

const baseUrl = `${import.meta.env.VITE_APP_BASE_URL || ""}/`;
const appointTime = ref<any>({
  year: "",
  date: "",
  start_time: "",
  end_time: "",
  orderStatus: null,
});
const appointText = ref<any>("");
const appoint = () => {
  if (!appointTime.value.date) {
    appointText.value = "请选择时间";
  } else {
    appointTime.value.year = new Date().getFullYear();
    const date = new Date();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    appointTime.value.date = `${month}-${day}`;
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    appointTime.value.start_time = `${hours}:${minutes}`;
    date.setHours(date.getHours() + 2);
    const hours2 = String(date.getHours()).padStart(2, "0");
    const minutes2 = String(date.getMinutes()).padStart(2, "0");
    appointTime.value.end_time = `${hours2}:${minutes2}`;
    console.log(appointTime.value);
    appointText.value = `${appointTime.value.date} ${appointTime.value.start_time}-${appointTime.value.end_time}`;
  }
};

const gIndexImage = reactive<{ img: string }>({
  img: "http://mzd-admin.muzhandao.com/api/uploads/image/20240905/3831e57f-f304-446a-a6fc-3572a7b964ad.png",
});
const orderData = ref<any>({
  order_amount: "",
  total_amount: "",
  total_goods_price: "",
  staff: [],
});
// const odr = ref<any>({
// 	order_amount: '',
// 	total_amount: '',
// 	total_goods_price: ''
// })
const payState = reactive({
  orderId: "",
  from: "",
  showPay: false,
  showCheck: false,
  redirect: "/pages/order_detail/index",
});
const orderId = ref<number | string>("");
const isBuy = ref<number>(0);
const BuyOrder = ref<any>({});

const isToggle = reactive({
  orderId: null,
  refundId: 0,
  refundAmount: 0,
  remark: null,
});
// 获取团购订单详情
const getBuyOrderData = async (): Promise<void> => {
  console.log(1111111);
  BuyOrder.value = await getBuyOrder({ orderId: orderId.value });
};

// 初始化订单详情
const initOrderDetail = async (): Promise<void> => {
  orderData.value = await apiOrderDetail({ id: orderId.value });
  isBuy.value = orderData.value.isBuy;

  if (isBuy.value == 1) {
    getBuyOrderData();
  }
};

const handlePayResult = async () => {
  payState.showPay = false;
  payState.showCheck = false;
  initOrderDetail();
};
const clickcardheader = async (header_order: any) => {
  console.log(header_order, "header_order");
  let openname =
    header_order.province +
    header_order.city +
    header_order.district +
    header_order.address;
  openLocationmap(
    header_order.latitude ? header_order.latitude : 22.553518,
    header_order.longitude ? header_order.longitude : 113.932923,
    openname
  );
};

const openLocationmap = async (latitude: any, longitude: any, name: any) => {
  uni.openLocation({
    latitude: Number(latitude),
    longitude: Number(longitude),
    scale: 17,
    name: name || "--",
    address: "",
  });
};

/**
		const navigateToAmap = async (latitude:any, longitude:any) => {
	
			const amapUrl = `androidamap://viewMap?sourceApplication=appname&poiname=myname&lat=${latitude}&lon=${longitude}&dev=0&style=2`;
			const iosUrl = `iosamap://path?sourceApplication=applicationName&dlat=${latitude}&dlon=${longitude}&dname=myname&dev=0&t=0`;
	
			// 判断平台并跳转
			if (uni.getSystemInfoSync().platform === 'android') {
				// 对于Android平台，使用高德地图的URL
				uni.navigateTo({
					url: amapUrl,
				});
			} else if (uni.getSystemInfoSync().platform === 'ios') {
				// 对于iOS平台，使用高德路线导航的URL
				uni.navigateTo({
					url: iosUrl,
				});
			} else {
				// 其他平台可能不支持直接调用高德地图，可以引导用户打开高德地图官网或使用内置的地图应用
				uni.navigateTo({
					url: '/pages/index/index', // 内置地图或提示用户打开高德地图官网页面
				});
			}
		}
	*/
const handleOrder = async (id: any) => {
  const res = await apiordergetOrderRefund({ orderId: id });
  console.log(res, "res---------");
  if (res == null) {
    isToggle.orderId = id;
    isToggle.refundId = 0;
  } else {
    isToggle.orderId = id;
    isToggle.refundId = res.id;
    isToggle.refundAmount = Number(res.refundAmount);
    isToggle.remark = res.remark;
  }
};
const bindChange = async (val: any) => {
  if (val <= orderData.value.totalAmount) {
    isToggle.refundAmount = val;
  }
};
// 提交退款申请，也可以直接进行更改
const dialogToggle = async () => {
  const res2 = await apiorderrebates(isToggle);
  console.log(res2, "res22222222222");
  uni.$u.toast("操作成功");
};

const onbuyPeople = async () => {
  console.log(BuyOrder.value[0].id, "BuyOrder");
  cache.set(GOODS_ID, orderData.value.goodsHostId);
  cache.set(ISBUY_ID, BuyOrder.value[0].id);
};

onShow(() => {
  uni.$on("payment", (param: any) => {
    payState.orderId = param.order_id;
    payState.from = param.from;
    payState.showPay = true;
    payState.redirect =
      payState.redirect +
      `?order_id=${param.order_id}&from=${param.from}&checkPay=true`;
  });
});
const paytype = ref(0);

onLoad((options: any) => {
  console.log(options);
  console.log("options");

  // 获取订单ID
  orderId.value = parseInt(options?.id);
  // 监听上门时间选择
  uni.$on("appointTime", (event) => {
    console.log("event");
    console.log(event);
    appointTime.value = {
      year: event.year,
      date: event.date,
      start_time: event.start_time,
      end_time: event.end_time,
      orderStatus: null,
    };
    appointText.value = `${appointTime.value.year}-${appointTime.value.date} ${appointTime.value.start_time}-${appointTime.value.end_time}`;
  });
  appoint();
  // 初始化订单信息
  initOrderDetail();

  // h5支付用于弹起手动确认支付弹窗
  if (options?.checkPay) {
    payState.orderId = options.order_id;
    payState.from = options.from;
    payState.showCheck = true;
    return;
  }
  if (options?.paytype == 1) {
    paytype.value = 1;
  } else if (options?.paytype == 2) {
    paytype.value = 2;
    appoint();
  }

  // 问号
  getgetIndexImage(5).then((res) => {
    gIndexImage.img = baseUrl + "api/uploads/" + res;
  });
});

onUnload(() => {
  uni.$off(["payment"]);
  payState.showPay = false;
});

onHide(() => {
  uni.$off(["payment"]);
});
const rightClick = () => {
  uni.redirectTo({ url: "/pages/order/index" });
};

// 跳转页面方法
const goPage = (url: string) => {
  uni.navigateTo({
    url,
  });
};

const refreshQryyfun = () => {
  if (appointTime.value.year == "") {
    uni.showModal({
      title: "提示",
      content: "请先选择时间",
      showCancel: false,
      confirmText: "好的",
    });
    return;
  }
  let data: any = {
    appointTimeStart:
      new Date(
        `${appointTime.value.year}-${appointTime.value.date} ${appointTime.value.start_time}:00`
      ).getTime() / 1000,
    appointTimeEnd:
      new Date(
        `${appointTime.value.year}-${appointTime.value.date} ${appointTime.value.end_time}:00`
      ).getTime() / 1000,
    goodsId: orderData.value.orderGoods.goodsId,
    orderStatus: 1,
    addressId: orderData.value.addressId,
    id: orderData.value.id,
  };

  apigetOrderupdate(data)
    .then((res) => {
      uni.$u.toast("预约成功");
      setTimeout(() => {
        uni.redirectTo({ url: "/pages/order/index" });
      }, 500);
    })
    .catch((orr) => {
      uni.$u.toast("预约失败");
    });
};
</script>

<style lang="scss">
.order_detail {
  height: 100%;
  margin-top: -45px;
  padding: 30rpx 24rpx;
  padding-bottom: 140rpx;
  /* background: linear-gradient(to bottom, #663d74 200rpx, transparent 0); */

  .header-image {
    width: 44rpx;
    height: 44rpx;
  }

  .card {
    padding: 24rpx;
    margin-bottom: 20rpx;
    background-color: #fff;
    border-radius: 10rpx;

    &--header {
      padding-bottom: 20rpx;
    }

    .title {
      font-weight: 500;
      color: #666;
      font-size: 32rpx;
    }
  }

  .goods-item {
    display: flex;

    &--name {
      width: 430rpx;

      // line-1
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}

.footer {
  left: 0;
  bottom: 0;
  width: 100%;
  height: 108rpx;
  position: fixed;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background-color: #ffffff;
  box-shadow: 2rpx 2rpx 22rpx rgba($color: #000000, $alpha: 0.2);

  .btn {
    width: 320rpx;
  }
}

.Btn {
  border: 1px solid rgba(187, 187, 187, 1);
  background-color: rgba(255, 255, 255, 1);
  color: rgba(16, 16, 16, 1);
  text-align: center;
}
.topImg {
  display: flex;
  width: 100vw;
  justify-content: center;
  .img_border {
    width: 50px;
    height: 50px;
    border-radius: 25px;
  }
}
.buyPeopleNum {
  width: 100vw;
  text-align: center;
  margin-top: 10px;
}
.footer_button {
  width: 100vw;
  margin: 20px 20px;
}
.topBg {
  background: url("http://mzd-admin.muzhandao.com/api/uploads/image/20240905/616405b5-39cd-4790-80e9-c608ff45ffb0.png");
  background-size: 100% 100%;
  width: 100vw;
  height: 476rpx;
  .u-navbar-fixed.u-border-bottom {
    /*  background: rgba(0,0,0,0)!important; */
  }
}
</style>